package is.web.htgen.single;

import is.bean.NamedEntity;
import is.bean.RemoteEntityAccess;
import is.web.Locale;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;

/**
 *
 * @author aspr0
 */
public class Select<Entity extends NamedEntity, BeanRemote extends RemoteEntityAccess<Entity>>
{
    private final String selectCanvas = "<select name=\"%s\" class=\"wide\">%s</select>";
    private final String optionCanvas = "<option value=\"%s\" %s>%s</option>";
    private boolean nullAllowed;
    private String selectName;
    private Integer selectedId;
    private Collection<BeanRemote> remotes;

    public void setNullAllowed(boolean nullAllowed)
    {
        this.nullAllowed = nullAllowed;
    }

    public void setSelectName(String selectName)
    {
        this.selectName = selectName;
    }

    public void setSelectedId(Integer selectedId)
    {
        this.selectedId = selectedId;
    }

    public void setRemotes(Collection<BeanRemote> remotes)
    {
        this.remotes = remotes;
    }

    public String generate() throws RemoteException
    {
        Iterator<BeanRemote> i = remotes.iterator();
        String options = (nullAllowed) ? String.format(optionCanvas, "", "", Locale.NULL_READABLE) : "";

        while (i.hasNext())
        {
            Entity entity = i.next().getData();
//System.out.println(entity.getName()+" "+entity.getClass()); //todo remove

            Integer id = entity.getId();
            String name = entity.getName();
            String selected = (id.equals(selectedId)) ? "selected" : "";

            options += String.format(optionCanvas, id, selected, name);
        }

        return String.format(selectCanvas, selectName, options);
    }
}
